package org.egrit.testutil;

import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.CountDownLatch;

import javax.swing.SwingUtilities;

import com.vividsolutions.jts.geom.Polygon;

import org.jaitools.swing.JTSFrame;

/**
 *
 * @author michael
 */
public class WaitingPolygonFrame {

    public static CountDownLatch show(final String title, final Polygon... polys) throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);
        if (SwingUtilities.isEventDispatchThread()) {
            doShow(latch, title, polys);
        } else {
            SwingUtilities.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    doShow(latch, title, polys);
                }
            });
        }
        return latch;
    }

    private static void doShow(CountDownLatch latch, String title, Polygon... polys) {
        WaitingJTSFrame frame = new WaitingJTSFrame(title, latch);
        frame.setSize(300, 300);
        frame.setVisible(true);
        for (Polygon poly : polys) {
            frame.addGeometry(poly, Color.RED);
        }
    }

    private static class WaitingJTSFrame extends JTSFrame {

        private final CountDownLatch closeLatch;

        WaitingJTSFrame(String title, CountDownLatch latch) {
            super(title);
            this.closeLatch = latch;
            addWindowListener(new WindowAdapter() {

                @Override
                public void windowClosing(WindowEvent e) {
                    closeLatch.countDown();
                }
            });
        }
    }
    
}
